/**
 * Created by wangp on 2016/8/25.
 */
$(function () {
    if (isLogin()) {
        /**
         * 个人中心首页
         */
        //加载用户信息
        var user = getUserInfo(), sex = {
            1: '帅哥',
            2: '美女'
        };



        /**
         * 设置用户信息
         */
        $('.userinfo .mui-pull-right.nickname').text(user.nickname);
        $('.userinfo .mui-pull-right.sex').text(sex[user.sex]);
        //地址选择器点击事件
        $('#address').on('tap', function () {
            var cityPicker3 = new mui.PopPicker({
                layer: 3
            });
            cityPicker3.setData(cityData3);
            cityPicker3.show(function (items) {
                user.liveAddress = (items[0] || {}).text + (items[1] || {}).text + (items[2] || {}).text;
            });
        });
        //性别选择器
        $('body').on('tap', '.mui-popover-action li>a', function () {
            var a = this,
                parent;
            //根据点击按钮，反推当前是哪个actionsheet
            for (parent = a.parentNode; parent != document.body; parent = parent.parentNode) {
                if (parent.classList.contains('mui-popover-action')) {
                    break;
                }
            }
            //关闭actionsheet
            mui('#' + parent.id).popover('toggle');
            $('.userinfo .mui-pull-right.sex').text(this.innerHTML);
            user.sex = $(this).data('type');
        });
        //保存用户信息
        $('.save-info').on('tap', function () {
            var data = {
                apiCode: '_update_userinfo_001',
                userToken: user.userToken,
                sex: user.sex
            };
            if (user.liveAddress) {
                data.liveAddress = user.liveAddress;
            }
            http(data, function (responed) {
                if (responed.error == 0) {
                    mui.toast('用户信息更新成功');
                    $.cookie('userInfo', JSON.stringify(user));
                    setTimeout(function () {
                        location.reload();
                    }, 2000);
                } else {
                    mui.alert(responed.info);
                }
            });
        });
        $('.img-item-box').on('tap', function(){
            $('.file-box input').trigger('click');
        });
        $('.file-box input').on('change', function(){
            var data = {
                apiCode: '_update_userinfo_001',
                userToken: user.userToken,
                download: new FormData($(this).parent('.form')[0])
            };
            http(data, function (responed) {
                if (responed.error == 0) {
                    mui.toast('用户信息更新成功');
                    $.cookie('userInfo', JSON.stringify(user));
                    setTimeout(function () {
                        location.reload();
                    }, 2000);
                } else {
                    mui.alert(responed.info);
                }
            });
        });
        /**
         * 修改用户昵称
         */
        $('.user-nickname input[name="nickname"]').val(user.nickname);
        $('#save-nickname').on('tap', function () {
            var _nickname = $('.user-nickname input[name="nickname"]'),
                nickname = $.trim(_nickname.val());
            if (!nickname) {
                mui.toast('请输入您的昵称');
                _nickname.focus();
                return false;
            }
            var data = {
                apiCode: '_update_userinfo_001',
                userToken: user.userToken,
                nickname: nickname
            };
            http(data, function (responed) {
                if (responed.error == 0) {
                    mui.toast('昵称修改成功');
                    user.nickname = nickname;
                    $.cookie('userInfo', JSON.stringify(user));
                    setTimeout(function () {
                        location.href = 'userinfo.html';
                    }, 1000);
                } else {
                    mui.alert(responed.info);
                }
            });
        });
        /**
         * 用户收货地址
         */
        window.receipt = (function (mui, _this, undefined) {
            var getReceipt = function () {
                var data = {
                    apiCode: '_receipt_001',
                    userToken: user.userToken
                };
                http(data, function (responed) {
                    if (responed.error == 0) {
                        for( var i in responed.info ){
                            var item = responed.info[i];
                            $('.mui-content').append('<div class="receipt-item">'+
                                '<div class="item-body">'+
                                '<div class="cell">'+
                                '<div class="info">收货人：<span class="name">'+item.username+'</span><div class="phone">'+item.phone+'</div></div>'+
                                '<div class="address">'+item.province+item.city+item.area+item.address+'</div>'+
                                '</div>'+
                                '<div class="cell"></div>'+
                                '</div>'+
                                '<div class="item-footer mui-row">'+
                                '<div class="mui-pull-left isdefault" data-id="'+item.id+'"><i class="icon-btn checkbox-btn '+(item.isdefault == 1 ? 'active' : '')+'"></i>默认</div>'+
                                '<div class="mui-pull-right"><span class="del-box" data-id="'+item.id+'"><i class="icon-btn del-btn"></i>删除</span><a href="user_receipt_add.html?id='+item.id+'"><i class="icon-btn edit-btn"></i>编辑</a></div>'+
                                '</div>'+
                                '</div>');
                        }
                    } else {
                        mui.alert(responed.info);
                    }
                });
            };
            var getReceiptInfo = function () {
                $('.receipt-add form').validate();
                var id = getUrlParam('id');
                if( !id )   return false;
                var data = {
                    apiCode: '_receipt_002',
                    userToken: user.userToken,
                    id: id
                };
                _this.id = id;
                http(data, function (responed) {
                    if (responed.error == 0) {
                        _this.receipt_desc = getPicker(cityData3,responed.info.province,responed.info.city,responed.info.area);
                        $('input[name="username"]').val(responed.info.username);
                        $('input[name="phone"]').val(responed.info.phone);
                        $('textarea[name="address_desc"]').val(responed.info.address);
                        responed.info.isdefault == 2 && $('#switch-default').removeClass('mui-active');
                        $('input[name="address"]').val(responed.info.province + ' ' + responed.info.city + ' ' +responed.info.area);
                    } else {
                        mui.alert(responed.info);
                    }
                });
            };
            _this.receipt_desc = {
                province: '',
                city: '',
                area: ''
            };
            $('.mui-content').on('tap', '.isdefault', function () {
                var id = $(this).data('id');
                mui.confirm('设置当前收货地址为默认?', '', ['确定', '取消'], function(e){
                    if( e.index == 0 ){
                        var data = {
                            apiCode: '_change_default_receipt_001',
                            userToken: user.userToken,
                            id: id
                        };
                        http(data, function (responed) {
                            if (responed.error == 0) {
                                mui.toast('设置成功');
                                setTimeout(function () {
                                    location.reload();
                                }, 1000);
                            } else {
                                mui.alert(responed.info);
                            }
                        });
                    }
                });
            });
            $('.mui-content').on('tap', '.del-box', function () {
                var id = $(this).data('id');
                mui.confirm('删除当前收货地址?', '', ['确定', '取消'], function(e){
                    if( e.index == 0 ){
                        var data = {
                            apiCode: '_delete_receipt_001',
                            userToken: user.userToken,
                            id: id
                        };
                        http(data, function (responed) {
                            if (responed.error == 0) {
                                mui.toast('删除成功');
                                setTimeout(function () {
                                    location.reload();
                                }, 1000);
                            } else {
                                mui.alert(responed.info);
                            }
                        });
                    }
                });
            });


            $('input[name="address"]').on('tap', function () {
                var self = $(this);
                var cityPicker3 = new mui.PopPicker({
                    layer: 3
                });
                cityPicker3.setData(cityData3);
                if (Object.keys(_this.receipt_desc.province).length) {
                    cityPicker3.pickers[0].setSelectedValue(_this.receipt_desc.province.value);
                }
                if (Object.keys(_this.receipt_desc.city).length) {
                    setTimeout(function () {
                        cityPicker3.pickers[1].setSelectedValue(_this.receipt_desc.city.value);
                    }, 100);
                }
                if (Object.keys(_this.receipt_desc.area).length) {
                    setTimeout(function () {
                        cityPicker3.pickers[2].setSelectedValue(_this.receipt_desc.area.value);
                    }, 200);
                }
                cityPicker3.show(function (items) {
                    var province = items[0] || {},
                        city = items[1] || {},
                        area = items[2] || {};
                    self.val(province.text + ' ' + city.text + ' ' + area.text);
                    _this.receipt_desc.province = province;
                    _this.receipt_desc.city = city;
                    _this.receipt_desc.area = area;
                });
            });

            $('#save-receipt').on('tap', function(){
                var username = $('input[name="username"]'),
                    phone = $('input[name="phone"]'),
                    address = $('textarea[name="address_desc"]'),
                    province = _this.receipt_desc.province,
                    city = _this.receipt_desc.city,
                    area = _this.receipt_desc.area,
                    _default = $('#switch-default').hasClass('mui-active');
                if( !username.val() ){
                    mui.toast('请输入联系人');
                    username.focus;
                    return false;
                }
                if( !phone.val() ){
                    mui.toast('请输入联系电话');
                    phone.focus;
                    return false;
                }
                if( !Object.keys(province).length || !Object.keys(city).length ){
                    mui.toast('请选择收货地址');
                    address.focus;
                    return false;
                }
                if( !address.val() ){
                    mui.toast('请输入详细收获地址');
                    address.focus;
                    return false;
                }
                var data = {
                    apiCode: '_set_receipt_001',
                    userToken: user.userToken,
                    province: province.text,
                    city: city.text,
                    area: area.text,
                    address: address.val(),
                    username: username.val(),
                    phone: phone.val(),
                    isdefault: (_default ? 1 : 2)
                };
                if( _this.id ){
                    data.id = _this.id;
                }
                http(data, function (responed) {
                    if (responed.error == 0) {
                        mui.toast(_this.id ? '编辑收货地址成功' : '新增收货地址成功');
                        setTimeout(function () {
                            location.href = 'user_receipt.html';
                        }, 1000);
                    } else {
                        mui.alert(responed.info);
                    }
                });
            });
            return {
                getReceipt: function () {
                    return getReceipt();
                },
                getReceiptInfo: function () {
                    return getReceiptInfo();
                }
            };
        })(mui, this);
        $('#btn-beedback').on('tap', function(){
            var text = $.trim($('.beedback-box textarea[name="text"]').val());
            if( !text ) return false;
            var data = {
                apiCode: '_beedback_001',
                userToken: user.userToken,
                content: text
            };
            http(data, function (responed) {
                if (responed.error == 0) {
                    mui.toast('我们已收到您的反馈信息');
                    setTimeout(function () {
                        location.href = 'set.html';
                    }, 1000);
                } else {
                    mui.alert(responed.info);
                }
            });
        });
    }
    function getPicker(list, province, city, area){
        var obj = {};
        if( typeof list != 'object' || !Object.keys(list).length)   return obj;
        for( var i in list ){
            var p_item = list[i];
            if( p_item.text == province ){
                obj.province = p_item;
                for( var j in p_item.children ){
                    var c_item = p_item.children[j];
                    if( c_item.text == city ){
                        obj.city = c_item;
                        for( var j in c_item.children ){
                            var a_item = c_item.children[j];
                            if( a_item.text == area ){
                                obj.area = a_item;
                            }
                        }
                    }
                }
            }
        }
        return obj;
    }
});
